﻿using System;
using System.Transactions;
using Abp.Dependency;
using Abp.Domain.Uow;
using Abp.EntityFrameworkCore.Uow;
using Abp.MultiTenancy;
using Vecen.BangChuang.EntityFrameworkCore.Seed.Host;
using Vecen.BangChuang.EntityFrameworkCore.Seed.Tenants;
using Microsoft.EntityFrameworkCore;
using Vecen.BangChuang.EntityFrameworkCore.Seed.BangChuang;

namespace Vecen.BangChuang.EntityFrameworkCore.Seed {
    public static class SeedHelper {
        public static void SeedHostDb(IIocResolver iocResolver) {
            WithDbContext<BangChuangDbContext>(iocResolver, SeedHostDb);
        }

        public static void SeedHostDb(BangChuangDbContext context) {
            context.SuppressAutoSetTenantId = true;

            //Host seed
            new InitialHostDbBuilder(context).Create();
            //tenant seed
            new InitialTenantDbBuilder(context).Create();

            //bangchuang seed
            new InitialBangChuangDbBuilder(context).Create();
        }

        private static void WithDbContext<TDbContext>(IIocResolver iocResolver, Action<TDbContext> contextAction)
            where TDbContext: DbContext {
            using(var uowManager = iocResolver.ResolveAsDisposable<IUnitOfWorkManager>()) {
                using(var uow = uowManager.Object.Begin(TransactionScopeOption.Suppress)) {
                    var context = uowManager.Object.Current.GetDbContext<TDbContext>(MultiTenancySides.Host);

                    contextAction(context);

                    uow.Complete();
                }
            }
        }
    }
}